package my.stock.util;

import lombok.SneakyThrows;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HttpUtil {

    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private ChromeDriver browser;

    private static int CALL_COUNT = 0;

    @SneakyThrows
    public String sendRequest(String url) {
        Request request = new Request.Builder()
                .url(url)
//                .addHeader("sec-ch-ua", "Google Chrome\";v=\"111\", \"Not(A:Brand\";v=\"8\", \"Chromium\";v=\"111")
//                .addHeader("sec-ch-ua-mobile", "?0")
//                .addHeader("sec-ch-ua-platform", "Windows")
//                .addHeader("Sec-Fetch-Dest", "document")
//                .addHeader("Sec-Fetch-Mode", "navigate")
//                .addHeader("Sec-Fetch-Site", "same-origin")
//                .addHeader("Sec-Fetch-User", "?1")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
//                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
//                .addHeader("Accept-Encoding", "gzip, deflate, br")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                .addHeader("Cookie", "v=A-8XJFSa11RjINNoRMKinxamfgj8lEO23ehHqgF8i95lUAG2CWTTBu241_sS")
//                .addHeader("Upgrade-Insecure-Requests", "1")
                .build();

        // 处理响应
        Response response = okHttpClient.newCall(request).execute();
        assert response.body() != null;
        return response.body().string();
    }

    @SneakyThrows
    public String openUrl(String url) {
        // 调用次数过多时，会出现 nginx forbidden
        if (CALL_COUNT++ == 5) {
            browser.navigate().to("https://www.10jqka.com.cn");
            Thread.sleep(2000);
            CALL_COUNT = 0;
        } else {
            Thread.sleep(500);
        }

        // 每次只保留一个页签，防止占用资源过多
        browser.navigate().to(url);

        return browser.getPageSource();
    }
}
